package com.cyy.demo.controller;

import com.cyy.demo.service.AsyncService;
import com.cyy.demo.service.FileService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

@Slf4j
@RestController
public class AsyncController {

    public AsyncController() {
        System.out.println("AsyncController开始创建");
    }

    @Autowired
    private AsyncService asyncService;

    @Autowired
    private FileService fileService;

    @GetMapping("/async")
    public String testAsync(){
        log.info("async controller start");
        long start = System.currentTimeMillis();
        asyncService.async();
        log.info("async controller end");
        long totalTime = System.currentTimeMillis()-start;
        log.info("总耗时:{}",totalTime);
        return "总耗时:"+totalTime;
    }

    @GetMapping("/async2")
    public String testAsync2(){
        log.info("async controller start");
        long start = System.currentTimeMillis();
        Future<String> future= asyncService.async2();
        String res = null;
        try {
            res = future.get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        log.info("async controller end");
        long totalTime = System.currentTimeMillis()-start;
        log.info("总耗时:{}",totalTime);
        return "总耗时:"+totalTime + "结果" + res;
    }


    @GetMapping("/sync")
    public String testSync(){
        log.info("sync controller start");
        long start = System.currentTimeMillis();
        asyncService.sync();
        log.info("async controller end");
        long totalTime = System.currentTimeMillis()-start;
        log.info("总耗时:{}",totalTime);
        return "总耗时:"+totalTime;
    }
}
